package com.huluobo.kotlinim2006a.contract.register

import android.text.TextUtils
import com.huluobo.kotlinim2006a.extention.isValidPassword
import com.huluobo.kotlinim2006a.extention.isValidUserName
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import org.jetbrains.anko.doAsync

/**
 * Created by lc on 2023/2/3.
 */
class RegisterPresenter(val view: RegisterContract.View) : RegisterContract.Presenter {
    override fun register(userName: String, password: String, confirmPassword: String) {
        if (userName.isValidUserName()) {
            if (password.isValidPassword()) {
                if (TextUtils.equals(password, confirmPassword)) {
                    //开启注册
                    view.onStartRegister()
                    registerEaseMob(userName, password)
                } else view.onConfirmPasswordError()
            } else view.onPasswordError()
        } else view.onUserNameError()
    }

    //模拟公司后台的操作流程,正常来讲不需要在移动端去注册
    private fun registerEaseMob(userName: String, password: String) {
        doAsync {
            try {
                //如果没有发生异常,则代表注册成功
                EMClient.getInstance().createAccount(userName, password)
                runOnUIThread {
                    view.onRegisterSuccess()
                }
            } catch (e: HyphenateException) {
                //如果捕获到异常,则代表注册失败
                runOnUIThread {
                    view.onRegisterFailed("注册环信失败:${e.message},code:${e.errorCode}")
                }
            }
        }
    }
}